﻿using DBModels;
using Models.operResult;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Api.WDS.Methods
{
    public class AccountMet
    {
        /// <summary>
        /// 用户注册的方法
        /// </summary>
        /// <param name="accounr">用户账号对象</param>
        /// <returns></returns>
        public OperResult<string> CreateUser(Account accounr)
        {
            using (ArticeContext context = new ArticeContext())
            {
                //用户信息
                var account = accounr;
                var userInfo = new UserInfo();
                using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        context.Entry(account).State = Microsoft.EntityFrameworkCore.EntityState.Added;
                        if (context.SaveChanges() is 1)
                        {
                            context.Entry(account);

                            #region 执行添加个人信息操作
                            userInfo.Id = account.Id;
                            userInfo.NickName = account.Id.ToString();
                            userInfo.Avatar = "default.jpg";
                            context.Entry(userInfo).State = Microsoft.EntityFrameworkCore.EntityState.Added;
                            if (context.SaveChanges() is 1)
                            {

                                #region Redis插入邮箱
                                new RedisHelper.User.Mail().InsertMail(account.Id.ToString(), account.Mail);
                                #endregion
                                #region Redis插入信息
                                new RedisHelper.User.UserInfo().InsertUserInfo(account.Id,new Models.RModels.R_UserInfo() { 
                                    Avatar = "default.jpg",
                                    NickName = account.Id.ToString(),
                                    Level = 0
                                });
                                #endregion

                                transaction.Commit();
                                return OperResult<string>.Succeed(account.Id.ToString());
                            }
                            #endregion
                        }

                        //回滚
                        transaction.Rollback();
                        return OperResult<string>.Failed("网络错误,请稍后重试");
                    }
                    catch (Exception ex)
                    {
                        //回滚
                        transaction.Rollback();
                        return OperResult<string>.Wrong(ex);
                    }
                }
            }
        }
    }
}
